import { create } from 'json-server'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { default as jsonServer } from 'json-server'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const server = jsonServer.create()
const router = jsonServer.router(join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()

// 设置默认中间件
server.use(middlewares)

// 自定义路由
server.use(jsonServer.bodyParser)
server.post('/api/login', (req, res) => {
  const { username, password } = req.body
  const db = router.db
  const user = db.get('users').find({ username, password }).value()
  
  if (user) {
    const { password, ...userWithoutPassword } = user
    res.json({
      code: 200,
      message: '登录成功',
      data: {
        token: 'mock-token',
        userInfo: userWithoutPassword
      }
    })
  } else {
    res.status(401).json({
      code: 401,
      message: '用户名或密码错误'
    })
  }
})

// 使用默认路由
server.use('/api', router)

// 启动服务器
server.listen(3000, () => {
  console.log('JSON Server is running on port 3000')
}) 